//
//  CGalleryView.m
//  HCHK_iphone
//
//  Created by yilong zhang on 11-12-7.
//  Copyright 2011年 __MyCompanyName__. All rights reserved.
//

#import "CGalleryView.h"

@implementation CGalleyItem

@synthesize m_delegate;
@synthesize m_nTag;
@synthesize m_ImageView;

-(id)initWithImage:(UIImage*)image
{
    self = [super initWithFrame:CGRectMake(0, 0, 0, 0)];
    if (self)
    {
        m_ImageView = [[UIImageView alloc] initWithFrame:CGRectMake(0, 0, 0, 0)];
        m_ImageView.image = image;
        m_ImageView.backgroundColor = [UIColor whiteColor];
        [self addSubview:m_ImageView];
        [m_ImageView release];
        
        m_nTag = 0;
    }
    
    return self;
}

-(void)dealloc
{
    [super dealloc];
}

-(void)SetPosition:(CGRect)position
{
    //16,15
    self.frame = position;
    /*self.m_ImageView.frame = CGRectMake(0, 0, position.size.height-18, position.size.height-18);
    CGFloat fsize = 0;
    if (position.size.width > position.size.height)
        fsize = position.size.height;
    else 
        fsize = position.size.width;*/
    self.m_ImageView.frame = CGRectMake(5, 5, position.size.width-10, position.size.height-10);
    //self.m_ImageView.center= CGPointMake(self.m_ImageView.center.x, self.frame.size.height/2);
    //self.m_ImageView.layer.borderColor = [[UIColor lightGrayColor] CGColor];
    //self.m_ImageView.layer.borderWidth = 1;
}

-(void)SetSelected
{
    [m_delegate DidGalleryItemSelected:self];
}


-(void)touchesEnded:(NSSet *)touches withEvent:(UIEvent *)event
{
    [m_delegate DidGalleryItemSelected:self];
}

@end

@implementation CGalleryView

@synthesize m_delegate;
@synthesize m_ItemsData;
@synthesize m_bIsHorizontal;
@synthesize m_RootScroll;
@synthesize m_bIsDrag;
@synthesize m_ScrollOffset;
@synthesize m_RootPanel;
@synthesize m_FocusPanel;
@synthesize m_FocusView;
@synthesize m_nOldFocus;
@synthesize m_nPages;
@synthesize m_nItemsNum;
@synthesize m_nPageItems;
@synthesize m_bIsPageEnd;
@synthesize m_nMoveDirection;
@synthesize m_nStartIndex;
@synthesize m_IndicatorView;
@synthesize m_Indicator;
@synthesize m_OldOffset;


- (id)initWithFrame:(CGRect)frame ItemSize:(CGSize)itemsize Horizontal:(BOOL)horizontal
{
    self = [super initWithFrame:frame];
    if (self) 
    {
        [self InitGalleryView:frame ItemSize:itemsize Horizontal:horizontal];
    }
    return self;
}

-(void)dealloc
{
    [super dealloc];
}

-(void)InitGalleryView:(CGRect)frame ItemSize:(CGSize)itemsize Horizontal:(BOOL)horizontal;
{
    m_nItemsNum  = 0;
    m_nPages     = 0;
    m_nPageItems = 0;
    m_bIsHorizontal = horizontal;
    m_nMoveDirection= -1;
    m_nStartIndex = 0;
    m_bIsPageEnd = NO;

    if (m_bIsHorizontal)
    {
        m_RootScroll = [[UIScrollView alloc] initWithFrame:CGRectMake(0, 0, frame.size.width, frame.size.height)];
        
    }
    else 
    {
        m_RootScroll = [[UIScrollView alloc] initWithFrame:CGRectMake(0, 0, frame.size.width, frame.size.height)];
    }
    m_bIsDrag = NO;
    m_RootScroll.contentSize = CGSizeMake(m_RootScroll.frame.size.width+1, 0);
    m_ScrollOffset = CGPointMake(0, 0);
    m_RootScroll.delegate = self;
    m_RootScroll.pagingEnabled = NO;
    m_RootScroll.decelerationRate = 0.0;
    m_RootScroll.delaysContentTouches = NO;
    m_RootScroll.backgroundColor = [UIColor clearColor];
    m_RootScroll.showsVerticalScrollIndicator = NO;
    m_RootScroll.showsHorizontalScrollIndicator = NO;
    [self addSubview:m_RootScroll];
    [m_RootScroll release];
    
    //gallery
    m_FocusPanel = [[UIView alloc] initWithFrame:CGRectMake(0, 0, 0, 0)];
    m_FocusPanel.backgroundColor = [UIColor clearColor];
    m_FocusPanel.userInteractionEnabled = NO;
    m_FocusPanel.clipsToBounds = YES;
    m_FocusPanel.alpha = 1.0;
    [m_RootScroll addSubview:m_FocusPanel];
    [m_FocusPanel release];
    
    m_nOldFocus = 0;
    /*CGFloat fsize = 0;
    if (ICON_WIDTH > ICON_HEIGHT)
        fsize = ICON_HEIGHT;
    else 
        fsize = ICON_WIDTH;*/
    m_FocusView = [[UIImageView alloc] initWithFrame:CGRectMake(5, 5, ICON_WIDTH-10, ICON_HEIGHT-10)];
    m_FocusView.image = [UIImage imageNamed:@"foucs.png"];
    //m_FocusView.center = CGPointMake(m_FocusView.center.x, self.frame.size.height/2);
    m_FocusView.backgroundColor = [UIColor clearColor];
    m_FocusView.userInteractionEnabled = NO;
    [m_FocusPanel addSubview:m_FocusView];
    [m_FocusView release];
    
    m_RootPanel = [[UIView alloc] initWithFrame:CGRectMake(0, 0, 0, 0)];
    m_RootPanel.backgroundColor = [UIColor clearColor];
    [m_RootScroll addSubview:m_RootPanel];
    [m_RootPanel release];
    
    [m_RootScroll bringSubviewToFront:m_FocusPanel];
    
    //indicatorview
    m_IndicatorView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, ICON_HEIGHT, ICON_HEIGHT)];
    m_IndicatorView.backgroundColor = [UIColor clearColor];
    m_IndicatorView.center = CGPointMake(m_IndicatorView.center.x, self.frame.size.height/2);
    m_IndicatorView.hidden = YES;
    [m_RootScroll addSubview:m_IndicatorView];
    [m_IndicatorView release];
    
    UIView *borderview = [[UIView alloc] initWithFrame:CGRectMake(0, 0, ICON_HEIGHT, ICON_HEIGHT)];
    borderview.backgroundColor = [UIColor lightGrayColor];
    //borderview.layer.borderColor = [[UIColor lightGrayColor] CGColor];
    //borderview.layer.borderWidth = 1;
    //borderview.backgroundColor = [UIColor clearColor];
    //borderview.center = CGPointMake(borderview.center.x, m_IndicatorView.frame.size.height/2);
    [m_IndicatorView addSubview:borderview];
    [borderview release];
    
    m_Indicator = [[UIActivityIndicatorView alloc] initWithActivityIndicatorStyle:UIActivityIndicatorViewStyleGray];
    m_Indicator.frame = CGRectMake(0, 0, 20, 20);
    m_Indicator.center= CGPointMake(borderview.center.x, m_IndicatorView.frame.size.height/2);
    [m_IndicatorView addSubview:m_Indicator];
    [m_Indicator release];
}

-(void)ResetGallery
{
    m_nItemsNum  = 0;
    m_nPages     = 0;
    m_nPageItems = 0;
    m_bIsDrag = NO;
    m_bIsPageEnd = NO;

    m_nMoveDirection = -1;
    m_nStartIndex = 0;
    id delegate = m_RootScroll.delegate;
    m_RootScroll.delegate = nil;
    m_RootScroll.contentSize = CGSizeMake(m_RootScroll.frame.size.width+1, 0);
    [m_RootScroll setContentOffset:CGPointMake(1, 0)];
    m_RootScroll.delegate = delegate;
    m_RootPanel.frame = CGRectMake(0, 0, 0, 0);
    m_FocusPanel.frame = CGRectMake(0, 0, 0, 0);
    m_FocusView.frame = CGRectMake(5, 5, ICON_WIDTH-10, ICON_HEIGHT-10);
    m_FocusView.tag = 0;
    m_nOldFocus = 0;
    
    for (CGalleyItem *item in [m_RootPanel subviews])
    {
        [item removeFromSuperview];
    }
    
    [self HiddenIndicator];
    m_IndicatorView.frame = CGRectMake(0, 0, ICON_WIDTH, ICON_WIDTH);
}

/*
// Only override drawRect: if you perform custom drawing.
// An empty implementation adversely affects performance during animation.
- (void)drawRect:(CGRect)rect
{
    // Drawing code
}
*/

-(void)ResetLoyout:(UIInterfaceOrientation)inerfaceorientation
{
    /*CGRect rect = [[UIScreen mainScreen] bounds];
   
    if (UIInterfaceOrientationLandscapeRight == inerfaceorientation || UIInterfaceOrientationLandscapeLeft == inerfaceorientation)
    {
        self.frame = CGRectMake(0, rect.size.width-44-40, rect.size.height, 40);
        m_RootScroll.frame = CGRectMake(0, 0, rect.size.height, 40);
    }
    else 
    {
        self.frame = CGRectMake(0, rect.size.height-44-40, rect.size.width, 40);
        m_RootScroll.frame = CGRectMake(0, 0, rect.size.width, 40);
    }*/
}

-(int)SetItems:(NSArray*)items Item:(CGalleyItem*)item
{
    m_RootScroll.scrollEnabled = NO;
    
    int        nIndex  = [[m_RootPanel subviews] count];
    CGalleyItem *Item  = nil;
    
    if (items)
    { 
        float fw = 0;
         
        for (int i=0; i<[items count]; i++)
        {
            ++m_nItemsNum;
            
            Item = [items objectAtIndex:i];
            [Item SetPosition:CGRectMake(m_RootPanel.frame.size.width, 0, ICON_WIDTH, ICON_HEIGHT)];
            fw = m_nItemsNum*ICON_WIDTH;
            m_RootPanel.frame = CGRectMake(0, 0, fw, self.frame.size.height);
            m_FocusPanel.frame = CGRectMake(0, 0, fw, self.frame.size.height);
            
            if (m_RootPanel.frame.size.width > m_RootScroll.contentSize.width)
                m_RootScroll.contentSize = CGSizeMake(m_RootPanel.frame.size.width, self.frame.size.height);
            
            Item.m_delegate = self;
            Item.m_nTag = nIndex++;
            [m_RootPanel addSubview:Item];
        }
    }
    else {;}
    
    m_RootScroll.scrollEnabled = YES;
    
    return [[m_RootPanel subviews] count];
}

-(void)GetGalleryPages
{
    return;
    
    //计算条目能被分成多少页
    m_nPageItems = (m_bIsHorizontal) ? (self.frame.size.width/m_FocusView.frame.size.width+0.5) : (self.frame.size.height/m_FocusView.frame.size.height+0.5);
    NSRange range = {0, [[m_RootPanel subviews] count]-1};
    NSArray *m_Items = [[m_RootPanel subviews] subarrayWithRange:range]; 
    (0 == [m_Items count] % m_nPageItems) ? (m_nPages = [m_Items count] / m_nPageItems) : (m_nPages = [m_Items count] / m_nPageItems + 1);
}

- (void)scrollViewDidScroll:(UIScrollView *)scrollView
{
    return;
    
    int nIndex = 0;
    CGPoint point = scrollView.contentOffset;
    
    //more
    if ((point.x+scrollView.frame.size.width) - scrollView.contentSize.width > 50)
    {
        //NSLog(@"------->End");
        m_bIsPageEnd = YES;
        [m_delegate DidGalleryDragEnd:self];
        //[m_delegate DidGalleryBottom];
    }
    else if (point.x < -50)
    {
        ;//NSLog(@"<-------End");
    }
    else
    {
        if (m_nItemsNum > 0)
        {
            //确定滚动的方向
            if (scrollView.contentOffset.x < m_OldOffset.x)
            {
                //向右滚动
                m_nMoveDirection = ScrollRight;
                //NSLog(@"scrollViewDidScroll===向右滚动___%f", scrollView.contentOffset.x);
                nIndex = scrollView.contentOffset.x / ICON_WIDTH;
                [m_delegate DidGalleryTurnPage:nIndex Directory:m_nMoveDirection Object:self];
            }
            else if (scrollView.contentOffset.x > m_OldOffset.x)
            {
                //向左滚动
                m_nMoveDirection = ScrollLeft;
                nIndex = scrollView.contentOffset.x / ICON_WIDTH;
                [m_delegate DidGalleryTurnPage:nIndex Directory:m_nMoveDirection Object:self];
                //NSLog(@"scrollViewDidScroll===向左滚动");
            }
            else {;}
        }
    }
    
    m_OldOffset = point;
}

- (void)scrollViewDidEndScrollingAnimation:(UIScrollView *)scrollView
{
    return;
    
    NSLog(@"scrollViewDidEndScrollingAnimation");
    m_OldOffset = scrollView.contentOffset;
    m_nStartIndex = m_OldOffset.x/m_FocusView.frame.size.width;
    NSLog(@"index:%d", m_nStartIndex);
    [m_delegate DidGalleryTurnPage:m_nStartIndex Directory:m_nMoveDirection Object:self];
}

-(void)scrollViewWillBeginDragging:(UIScrollView *)scrollView
{
    return;
    
    m_RootScroll.scrollEnabled = YES;
    
    m_OldOffset = scrollView.contentOffset;
}

-(void)scrollViewDidEndDragging:(UIScrollView *)scrollView willDecelerate:(BOOL)decelerate
{
    return;
    
    int nIndex = 0;
    
    if (!decelerate)
    {
        if (scrollView.contentOffset.x > m_OldOffset.x)
        {
            m_nMoveDirection = ScrollLeft;
            nIndex = scrollView.contentOffset.x / m_FocusView.frame.size.width;
            [m_delegate DidGalleryTurnPage:nIndex Directory:m_nMoveDirection Object:self];
            NSLog(@"向左滚动");
        }
        else if (scrollView.contentOffset.x < m_OldOffset.x)
        {
            m_nMoveDirection = ScrollRight;
            nIndex = scrollView.contentOffset.x / m_FocusView.frame.size.width;
            [m_delegate DidGalleryTurnPage:nIndex Directory:m_nMoveDirection Object:self];
            NSLog(@"向右滚动");
        }
        NSLog(@"松开");
    }
}

- (void)scrollViewDidEndDecelerating:(UIScrollView *)scrollView
{  
    return;
    
    if (m_bIsPageEnd)
        [m_delegate DidGalleryBottom:self];
    
    m_bIsPageEnd = NO;
    return;
    
    int nIndex = 0;
    
    m_RootScroll.scrollEnabled = YES;
    
    NSLog(@"滚动停止");

    //确定滚动的方向
    if (scrollView.contentOffset.x < m_OldOffset.x)
    {
        //向右滚动
        m_nMoveDirection = ScrollRight;
        nIndex = scrollView.contentOffset.x / ICON_WIDTH;
        [m_delegate DidGalleryTurnPage:nIndex Directory:m_nMoveDirection Object:self];
        NSLog(@"向右滚动");
    }
    else if (scrollView.contentOffset.x > m_OldOffset.x)
    {
        //向左滚动
        m_nMoveDirection = ScrollLeft;
        nIndex = scrollView.contentOffset.x / m_FocusView.frame.size.width;
        [m_delegate DidGalleryTurnPage:nIndex Directory:m_nMoveDirection Object:self];
        NSLog(@"UIScrollView向左滚动");
    }
    
    m_OldOffset = scrollView.contentOffset;
}

- (void)scrollViewWillBeginDecelerating:(UIScrollView *)scrollView
{
    return;
    NSLog(@"将要松开");
    m_RootScroll.scrollEnabled = NO;
}

//new
-(void)CorrectScrollViewPosition:(UIScrollView*)scrollView
{
    return;
    
    int nTemp = (int)scrollView.contentOffset.x % (int)m_FocusView.frame.size.width;
    NSLog(@"%f___%f___%d", m_FocusView.frame.size.width, scrollView.contentOffset.x, nTemp);
    if (0 != nTemp)
    {
        if (ScrollLeft == m_nMoveDirection)
        {
            nTemp = m_FocusView.frame.size.width - nTemp;
            [scrollView setContentOffset:CGPointMake(scrollView.contentOffset.x + nTemp, scrollView.contentOffset.y) animated:YES];
        }
        else if (ScrollRight == m_nMoveDirection)
        {
            [scrollView setContentOffset:CGPointMake(scrollView.contentOffset.x - nTemp, scrollView.contentOffset.y) animated:YES];
        }
        else {;}
        NSLog(@"草");
    }
    else 
    {
        m_OldOffset = scrollView.contentOffset;
        m_nStartIndex = m_OldOffset.x/m_FocusView.frame.size.width;
        NSLog(@"index:%d", m_nStartIndex);
        [m_delegate DidGalleryTurnPage:m_nStartIndex Directory:m_nMoveDirection Object:self];
    }
}

-(void)UpdateScrollOffset;
{
    //more
    if (m_FocusView.tag-m_nOldFocus > 0)
    {
        [m_RootScroll scrollRectToVisible:m_FocusView.frame animated:YES];   
        
        m_nMoveDirection = 0;
    }
    //back
    else if (m_FocusView.tag-m_nOldFocus < 0)
    {
        [m_RootScroll scrollRectToVisible:m_FocusView.frame animated:YES];
        
        m_nMoveDirection = 1;
    }
    else {;}
}

-(void)SetFocusPosition:(int)index
{
    CGalleyItem *item = (CGalleyItem*)[[m_RootPanel subviews] objectAtIndex:index];
    
    m_nOldFocus = m_FocusView.tag;
    m_FocusView.frame = CGRectMake(item.frame.origin.x+5, item.frame.origin.y+5, m_FocusView.frame.size.width, m_FocusView.frame.size.height);
    m_FocusView.tag = index;
    
    [self UpdateScrollOffset];
}

-(void)DidSelected:(int)index
{
    if (1/*m_FocusView.tag != index*/)
    {
        [self SetFocusPosition:index];
        
        [m_delegate DidGallerySelected:index Directory:m_FocusView.tag-m_nOldFocus Object:self];
    }
}

-(void)DidGalleryItemSelected:(CGalleyItem *)item
{
    m_bIsDrag = YES;
    [self DidSelected:item.m_nTag];
}

-(void)ShowIndicator
{
    if (m_IndicatorView.hidden)
    {
        [m_Indicator startAnimating];
        m_RootScroll.contentSize = CGSizeMake(m_RootScroll.contentSize.width+m_IndicatorView.frame.size.width, m_RootScroll.contentSize.height);
        m_IndicatorView.tag = m_nItemsNum;
        m_IndicatorView.frame = CGRectMake(m_RootPanel.frame.size.width, m_IndicatorView.frame.origin.y, m_IndicatorView.frame.size.width, m_IndicatorView.frame.size.height);
        m_IndicatorView.hidden = NO;
    }
}

-(void)HiddenIndicator
{
    if (!m_IndicatorView.hidden)
    {
        [m_Indicator stopAnimating];
        m_IndicatorView.hidden = YES;
        if (m_IndicatorView.tag < [[m_RootPanel subviews] count])
        {
            CGalleyItem *item = [[m_RootPanel subviews] objectAtIndex:m_IndicatorView.tag];
            CProduct *product = [m_ItemsData objectAtIndex:m_IndicatorView.tag];
            item.m_ImageView.image = [UIImage imageWithData:[product GetProductIcon]];
        }
        else 
        {
            m_RootScroll.contentSize = CGSizeMake(m_RootScroll.contentSize.width-m_IndicatorView.frame.size.width, m_RootScroll.contentSize.height);
        }
    }
}

@end
